<template>
    <div>
        <!--查询条件start --111s-->
        <el-form :inline="true" :model="query" class="query-form" size="small">
            <el-form-item>
                <el-button type="primary" icon="el-icon-edit" @click.native="showDialogAddOrEdit(null,null)">添加 </el-button>
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="createTime"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="left"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00','23:59:59']"
                    @change="dateChange"
                ></el-date-picker>
            </el-form-item>
            <el-form-item class="query-form-item">
                <el-input
                    v-model="query.msgtitle"
                    placeholder="请输入用户名"
                    prefix-icon="el-icon-search"
                    @keyup.enter.native="onSubmit"
                    clearable
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-refresh" @click="onRest"></el-button>
                <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>

            </el-form-item>

        </el-form>
        <!--查询条件end-->

        <!--列表start --222s-->
        <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="list"
            :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
            @selection-change="handleSelectionChange"
            border
        >
            <el-table-column type="selection" width="50" fixed/>
            <el-table-column label="消息ID" prop="msgid" width="80" align="center"/>

            <el-table-column label="标题" prop="msgtitle" align="center"/>

            <el-table-column label="详情" prop="msgcontent" align="center">
                <template slot-scope="scope">
                    <div v-html="scope.row.msgcontent"></div>
                </template>
            </el-table-column>

            <el-table-column label="推送范围" prop="usertype" align="center" width="120">
                <template slot-scope="scope">
                    <span>{{ scope.row.usertype==0?'全部':'指定'}}    </span>

                </template>

            </el-table-column>

            <el-table-column label="发布时间" with="300" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" v-if="scope.row.msgtime!=null"></i>
                    <span
                        v-if="scope.row.msgtime!=null"
                    >{{ scope.row.msgtime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                    <span v-else>暂未登录</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button
                        type="primary"
                        size="mini"
                        @click.native="detailForm(scope.$index, scope.row)"
                    >查看
                    </el-button>
                    <el-button
                        type="danger"
                        size="mini"
                        @click.native="handleDel(scope.row.msgid)"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--列表end --222e-->

        <!--全选删除start-->
        <div class="left-container">
            <el-button type="danger" size="small" @click="delGroup()">删除已选</el-button>
            <transition name="el-fade-in-linear">
                <el-button size="small" @click="toggleSelection()" v-show="cancelToggle">取消选择</el-button>
            </transition>
        </div>
        <!--全选删除end-->

        <!--分页模块start-->
        <el-pagination
            class="pagination-container"
            background
            :page-size="query.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total,sizes,prev, pager, next, jumper"
            :current-page="query.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :total="totalNumber"
        ></el-pagination>
        <!--分页模块end-->

        <!--新增消息-->
        <el-dialog
            :title="dialogAddOrEditName"
            :visible.sync="dialogAddOrEdit"
            width="60%"
            :before-close="hideDialogAddOrEdit">
            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="标题" prop="msgtitle">
                    <el-input v-model="formData.msgtitle"></el-input>
                </el-form-item>
                <el-form-item label="详情" prop="msgcontent">
                 <!--   <el-input v-model="formData.msgcontent"></el-input>-->
                    <tinymce style="display: inline-block;width: 100%;" ref="tinymce" :height="200" v-model="formData.msgcontent"/>
                </el-form-item>
                <el-form-item label="推送范围" prop="">
                    <el-select v-model="formData.usertype" label="全部" placeholder="请选择推送范围" @change="selopt(formData.usertype)"
                               clearable>
                           <el-option label="全部推送" value="0"></el-option>
                           <el-option label="指定推送" value="1"></el-option>

                    </el-select>
                </el-form-item>
                <el-form-item label="用户名单" prop="" v-if="formData.usertype==='1'">
                    <div v-if="seloptshow">
                        <label >已选择全部用户</label>
                    </div>
                   <div v-else>
                   <!--  scope.row.userban==0?'允许登录':'禁止登录'}-->
                     <label >已选择 {{formData.userid===""? 0:formData.userid.split(",").length}}  用户</label>
                  <!--   <label >已选择 {{formData.userid.split(",").length}}  用户</label>-->
                     <el-button style="margin-left: 20px" :loading="formSumbitLoding" @click="showselectuser">
                         选择推送用户
                     </el-button>
                 </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogAddOrEdit = false">取 消</el-button>
    <el-button type="primary" :loading="formSumbitLoding" @click="formSumbit">提交</el-button>
  </span>
        </el-dialog>
        <!--选择用户-->
        <el-dialog
             title="选择推送用户"
            :visible.sync="dialoguser"
            width="60%"
            :before-close="hideDialogUser">
            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            </el-form>
            <template>
                <dev>
                    <!--列表start --222s-->
                    <el-table
                        ref="multipleTable"
                        v-loading="loading"
                        :data="userlist"
                        :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
                        @selection-change="userhandleSelectionChange"
                        border
                    >
                        <el-table-column type="selection" width="50" fixed/>
                        <el-table-column label="用户 ID" prop="userid" width="80" align="center"/>
                        <el-table-column label="头像" prop="userpic" align="center" width="200">
                            <template slot-scope="scope">
                                <el-popover v-if="scope.row.userpic" placement="right" trigger="hover">
                                    <img :src="scope.row.userpic" style="width:400px;border-radius:3px;">
                                    <img
                                        slot="reference"
                                        :src="scope.row.userpic"
                                        style="max-height: 80px;max-width: 50px;border-radius:5px;"
                                    >
                                </el-popover>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="用户昵称" prop="usernick" align="center"/>
                        <el-table-column label="手机号码" prop="usermobile" align="center"/>
                        <el-table-column label="注册时间" with="300" :show-overflow-tooltip="true" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-time" v-if="scope.row.userregisttime!=null"></i>
                                <span
                                    v-if="scope.row.userregisttime!=null"
                                >{{ scope.row.userregisttime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--列表end --222e-->
                    <!--分页模块start-->
                    <el-pagination
                        class="pagination-container"
                        background
                        :page-size="query2.pageSize"
                        @size-change="handleSizeChange2"
                        @current-change="handleCurrentChange2"
                        layout="total,sizes,prev, pager, next, jumper"
                        :current-page="query2.currentPage"
                        :page-sizes="[10, 20, 30, 50]"
                        :total="totalNumber2"
                    ></el-pagination>
                    <!--分页模块end-->
                </dev>
            </template>

            <span slot="footer" class="dialog-footer">
        <el-button @click="dialoguser = false">取 消</el-button>
        <el-button type="primary"  @click="userGroup">提交</el-button>
        </span>
        </el-dialog>

        <!--查看详细弹框-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="detailVisible"
            :before-close="hideDetailForm"
            width="700px"
            top="5vh"
            v-dialogDrag
        >
            <el-form :model="formData" label-width="140px">
                    <el-form-item label="标题：" >
                        <input v-model="formData.msgtitle" type="text" readonly>
                    </el-form-item>
                    <el-form-item label="消息内容" >
                      <!--  <input v-model="formData.msgcontent" type="text" readonly>-->
                        <div v-html="formData.msgcontent"></div>
                    </el-form-item>
                    <el-form-item label="推送类型" >
                        <span>{{formData.usertype==0?'全部':'指定'}}    </span>
                    </el-form-item>
                <el-form-item label="用户" >
                     <span >
                         {{listusers}}
                     </span>
                </el-form-item>

            </el-form>
        </el-dialog>

    </div>
</template>
<script>
    import {getList,getmsgList,addmsg,delmsg,getIdsUser} from "../../api/mbuser/mbuser";
    import Tinymce from "../../components/Tinymce/index.vue";
    /*用作表单的数据初始化*/
    const formJson = {
        msgtitle:"",
        usertype:"",
        msgcontent:"",
        userid:""
    };

    export default {
        components: {
            Tinymce
        },
        data() {
            return {
                pickerOptions: {//快速选择日期
                    shortcuts: [
                        {
                            text: "最近一周",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 7
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近一个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 30
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近三个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 90
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近六个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 180
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        }
                    ]
                },
                query: {//查询条件
                    msgtitle:"",
                    startTime: "",
                    endTime: "",
                    currentPage: 1,
                    pageSize: 10,
                },
                query2: {//查询条件 用户
                    currentPage: 1,
                    pageSize: 10,
                },
                detailVisible:false,
                formName:null, //
                formMap: {
                    add: "添加",
                    edit: "编辑",
                    detail: "详情"
                },
                listusers:"",
                createTime:[],//选择日期时需要的model
                list: [],//列表集合
                userlist:[],//选择用户列表
                totalNumber: 0,//分页总页数
                totalNumber2: 0,//分页总页数
                loading: true,//列表加载
                allLoding: false,//全屏加载
                formSumbitLoding: false,//表单提交加载
                cancelToggle: false,//列表是否全选
                cancelToggleuser:false,//用户列表是否全选
                multipleSelection: [], //多选集合
                multipleSelectionuser:[],//用户多选集合
                dialogAddOrEdit: false,//新增或编辑弹框开关
                dialoguser:false,  //选择用户列表
                seloptshow:false,  //显示选择
                dialogAddOrEditName: "",//新增或编辑弹框名字
                formData: formJson,//新增或修改的对象

                rules: {//表单校验

                    msgtitle: {
                        required: true,
                        message: "请输入标题",
                        trigger: "blur"
                    },
                    usertype: {
                        required: true,
                        message: "请输入推送类型",
                        trigger: "blur"
                    },
                    msgcontent: {
                        required: true,
                        message: "请输入消息内容",
                        trigger: "blur"
                    }


                }
            };
        },
        methods: {

            selopt(val){
              //  alert(val);
                if(val===0){
                    this.seloptshow=true;
                    this.formData.usertype=0;
                    this.formData.userid='';
                }else{
                    this.seloptshow=false;
                }
            },

            /*获取列表事件*/
            getList() {
                this.loading = true;
                getmsgList(this.query).then(response => {
                    if (response.code != 0) {
                        this.$message.error(response.message);
                        return false;
                    }
                    this.list = response.data.list || [];
                    this.totalNumber = response.data.totalNumber || 0;
                    setTimeout(() => {
                        this.loading = false;
                    }, 0.3 * 1000);
                }).catch(() => {
                    this.loading = false;
                    this.list = [];
                })
            },

            /*新增或者编辑提交事件*/
            formSumbit() {
                //表单校验通过
                this.$refs["ruleForm"].validate(valid => {
                    if (valid) {
                        this.formSumbitLoding = true;
                        let data=this.formData;
                        var params = new URLSearchParams(data);
                        console.info(data);
                        addmsg(params).then(response => {
                            this.formLoading = false;
                            if (response.code != 0) {
                                this.$message.error(response.message);
                                this.formSumbitLoding = false;
                               // this.dialogAddOrEdit = false;
                                return false;
                            }
                            this.$message.success("操作成功");
                            this.formData={};

                            this.formSumbitLoding = false;
                            this.dialogAddOrEdit = false;
                            // 加载表格数据
                            this.getList();
                            // 清空表单
                            this.$refs["dataForm"].resetFields();

                        });

                    }
                });
                //new URLSearchParams(this.query)  提交数据格式不正确时可以转一下
            },

            /*列表查询条件事件*/
            onSubmit() {
                this.query.currentPage = 1;
                this.$router.push({
                    path: "",
                    query: this.query
                });
                this.getList();
            },

            /*刷新*/
            onRest() {
                this.$router.push({
                    path: ""
                });
                //刷新事件需要重置查询条件
                this.createTime = [];
                this.query = {
                    currentPage: 1,
                    pageSize: 10,
                };
                this.getList();
            },
            showselectuser(){
                this.dialoguser=true;
                this.selectuser();
            },
            selectuser(){
              //  this.dialoguser = !this.dialoguser;

                this.loading = true;
                getList(this.query2).then(response => {
                    if (response.code != 0) {
                        this.$message.error(response.message);
                        return false;
                    }

                    this.userlist= response.data.list || [];
                    this.totalNumber2 = response.data.totalNumber || 0;
                    setTimeout(() => {
                        this.loading = false;
                    }, 0.3 * 1000);
                }).catch(() => {
                    this.loading = false;
                    this.userlist = [];
                })

            },

            //显示 查看弹框
            detailForm(index, row) {
                if (row !== null) {
                    this.detailVisible = true;

                    this.formData = Object.assign({}, row);
                    this.formName = "detail";

                    this.loading = true;
                    var params = new URLSearchParams();
                    params.append("ids", row.userid);
                    getIdsUser(params)
                        .then(response => {
                            this.loading = false;
                            if (response.code) {
                                this.$message.error(response.message);
                                return false;
                            }
                           // this.listusers=response.data;
                           let list= response.data;
                            let user;
                            this.listusers="";
                           for (let i=0;i<list.length;i++) {
                               if(user===undefined){
                                   user=list[i].usernick
                               }else{
                                   user+= ",  "+list[i].usernick;
                               }

                           }
                            this.listusers=user
                            console.info(666666666666+this.listusers);
                           // this.obj = Object.assign({}, this.formData, {listusers: response.data}) //（推荐写法）
                          // alert(this.listusers[0].usernick);
                            this.$message.success("获取成功");

                        })
                        .catch(() => {
                            this.loading = false;
                        });

                }
            },
            // 隐藏详情弹框
            hideDetailForm() {
                // 更改值
                this.detailVisible = !this.detailVisible;
                return true;
            },
            /*显示 -新增或者编辑弹框*/
            showDialogAddOrEdit(index, row) {
                this.dialogAddOrEdit = true;
                this.formData = Object.assign({}, formJson);//将弹框内表单内容初始化
                if (row !== null) {
                    //如果row不为空，说明是修改，因为row是修改时携带过来此列的所有信息
                    this.formData = Object.assign({}, row);//修改则将列内容深拷贝到表单内容中
                    this.dialogAddOrEditName = "编辑";
                } else {
                    this.dialogAddOrEditName = "新增";
                }
            },

            /*隐藏 -新增或编辑弹框*/
            hideDialogAddOrEdit() {
                this.dialogAddOrEdit = false;

                //隐藏弹框时需要清除弹框内容
                if (this.$refs["ruleForm"]) {
                    this.$refs['ruleForm'].resetFields();//清除formData表单
                    this.$refs["ruleForm"].clearValidate();//清除表单验证
                }
                //如果上传文件，还需要清除文件列表
            },

            hideDialogUser(){
                this.dialoguser=false;
            },
            /*点击页数*/
            handleCurrentChange(val) {
                this.query.currentPage = val;
                this.getList();
            },

            /*选择每页条数【10,20,30,40,50】*/
            handleSizeChange(val) {
                this.query.pageSize = val;
                this.getList();
            },

            /*用户点击页数*/
            handleCurrentChange2(val) {
                this.query2.currentPage = val;
                this.selectuser();
            },

            /*用户选择每页条数【10,20,30,40,50】*/
            handleSizeChange2(val) {
                this.query2.pageSize = val;
                this.selectuser();
            },



            /*取消全选事件*/
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },

            /*列表复选框选择事件*/
            handleSelectionChange(val) {
                this.multipleSelection = val;
                if (val == "") {
                    this.cancelToggle = false;
                    return;
                }
                this.cancelToggle = true;
            },

            /*用户列表复选框选择事件*/
            userhandleSelectionChange(val) {
           this.multipleSelectionuser = val;
           if (val == "") {
            this.cancelToggleuser = false;
            return;
           }
          this.cancelToggleuser = true;
          },

            /*全选删除事件*/
            delGroup() {
                console.log(this.multipleSelection)
                var ids = this.multipleSelection.map(item => item.msgid).join(); //获取所有选中行的id组成的字符串，以逗号分隔
                if (ids == "") {
                    this.$message({
                        message: "请先选择",
                        type: "warning"
                    });
                    return;
                }
                this.handleDel(ids);
            },

            /*用户请选择*/
            userGroup() {
                console.log(this.multipleSelectionuser)
                var ids = this.multipleSelectionuser.map(item => item.userid).join(); //获取所有选中行的id组成的字符串，以逗号分隔
                if (ids == "") {
                    this.$message({
                        message: "请先选择",
                        type: "warning"
                    });
                    return;
                }
                this.formData.userid=ids;
               // alert(this.formData.userid);

                this.dialoguser=false;
            },



            /*单击删除事件*/
            handleDel(ids) {
                if (ids) {
                    this.$confirm("确认要删除吗?", "提示", {
                        type: "warning"
                    })
                        .then(() => {

                            this.loading = true;
                            var params = new URLSearchParams();
                            params.append("ids", ids);
                            delmsg(params)
                                .then(response => {
                                    this.loading = false;
                                    if (response.code) {
                                        this.$message.error(response.message);
                                        return false;
                                    }
                                    this.$message.success("删除成功");
                                    // 刷新数据
                                    //this.list.splice(index, 1);
                                    this.getList();
                                })
                                .catch(() => {
                                    this.loading = false;
                                });
                        })
                        .catch(() => {
                            this.$message.warning("已取消");
                        });
                }
            },

            /*日期选择事件*/
            dateChange(val) {
                if (val == null) {
                    this.query.startTime = "";
                    this.query.endTime = "";
                } else {
                    this.query.startTime = val[0];
                    this.query.endTime = val[1];
                    this.query.currentPage = 1;
                }
                this.getList();
                console.log(this.query)
            },
        }, created() {
            this.getList();
        }
    }
    //跳转路由的方法
    // this.$router.push({
    //     path: "",
    //     query:{
    //         username:"张三"
    //     }
    // });
    //接受路由传递的参数
    //let query = this.$route.query;
</script>
